<template>
    <div class="container" v-loading="loading">
        <div>
            <div class="header-container-detail">
                <el-form label-width="100px">
                    <!-- <el-collapse>
                        <el-collapse-item>
                            <template slot="title"> -->
                    <el-row class="backGC">
                        <el-col :span="23">
                            <div class="display-grid1">
                                <el-form-item label="条目编码">
                                    <el-input v-model="staticResultDetailData.entryCode" placeholder="" readonly size="mini"></el-input>
                                </el-form-item>
                                <el-form-item label="条目名称">
                                    <el-input v-model="staticResultDetailData.entryName" placeholder="" readonly size="mini"></el-input>
                                </el-form-item>
                                <el-form-item label="估值日期">
                                    <el-date-picker
                                        v-model="tradeDate"
                                        type="date"
                                        placeholder="选择日期"
                                        readonly
                                        value-format="yyyyMMdd"
                                        format="yyyy-MM-dd"
                                        size="mini"
                                    >
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="触警类型">
                                    <el-input v-model="triggerType" readonly size="mini"></el-input>
                                </el-form-item>
                            </div>
                            <div class="display-grid1">
                                <el-form-item label="计算日期">
                                    <el-date-picker
                                        :value="getCalcDateTime(staticResultDetailData)"
                                        type="datetime"
                                        placeholder="选择日期时间"
                                        readonly
                                        size="mini"
                                    >
                                        <!-- moment(this.state.staticResult.calculateDate + ' ' + this.PrefixInteger(this.state.staticResult.calculateTime, 6), "YYYYMMDD HHmmss").format('YYYY-MM-DD HH:mm:ss')} -->
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="计算结果">
                                    <el-input v-model="calculateValue" placeholder="" readonly size="mini"></el-input>
                                </el-form-item>
                                <!-- this.state.staticResult.result == '0' ? this.state.staticResult.result : this.numberFormat(`${this.state.staticResult.result || ''}`) -->
                                <el-form-item label="连续违规日期">
                                    <el-input v-model="prohibitionDate" placeholder="" readonly size="mini"></el-input>
                                </el-form-item>
                                <el-form-item label="条目触发值">
                                    <el-input v-model="thresholdValue" placeholder="" readonly size="mini"></el-input>
                                </el-form-item>
                                <!-- {this.state.staticResult.result == '0' ? this.state.staticResult.result : this.numberFormat(`${this.state.staticResult.thresholdValue || ''}`)} -->
                            </div>
                        </el-col>
                        <el-col :span="1">
                            <div class="boxStyle" @click="rotateClick">
                                <span class="el-icon-arrow-down iconStyle" v-if="isOpen"></span>
                                <span class="el-icon-arrow-right iconStyle" v-else></span>
                            </div>
                        </el-col>
                    </el-row>
                    <!-- </template> -->
                    <!-- <el-row style="border-top: 1px solid #ccc">
                                <el-col :span="24">
                                    <div class="display-grid1">
                                        <el-form-item label="流水号">
                                            <el-input v-model="staticResultDetailData.resultId" placeholder="" readonly size="mini"></el-input>
                                        </el-form-item>
                                        <el-form-item label="静态条目KEY">
                                            <el-input v-model="staticResultDetailData.entryKey" placeholder="" readonly size="mini"></el-input>
                                        </el-form-item>
                                        <el-form-item label="条目比较方向">
                                            <el-input v-model="compareType" readonly size="mini"></el-input>
                                        </el-form-item>
                                        <el-form-item label="逻辑分支顺序">
                                            <el-input
                                                v-model="staticResultDetailData.calculateBranchNos"
                                                placeholder=""
                                                readonly
                                                size="mini"
                                            ></el-input>
                                        </el-form-item>
                                    </div>
                                    <div class="display-grid2">
                                        <el-form-item label="计算逻辑">
                                            <el-input v-model="staticResultDetailData.calculateLogic" placeholder="" readonly size="mini"></el-input>
                                        </el-form-item>
                                        <el-form-item label="错误信息">
                                            <el-input v-model="staticResultDetailData.errorMessage" placeholder="" readonly size="mini"></el-input>
                                        </el-form-item>
                                    </div>
                                </el-col>
                            </el-row> -->
                    <!-- </el-collapse-item>
                    </el-collapse> -->

                    <el-row v-if="isOpen" style="border-top: 1px solid #ccc">
                        <el-col :span="23">
                            <div class="display-grid1">
                                <el-form-item label="流水号">
                                    <el-input v-model="staticResultDetailData.resultId" placeholder="" readonly size="mini"></el-input>
                                </el-form-item>
                                <el-form-item label="静态条目KEY">
                                    <el-input v-model="staticResultDetailData.entryKey" placeholder="" readonly size="mini"></el-input>
                                </el-form-item>
                                <el-form-item label="条目比较方向">
                                    <el-input v-model="compareType" readonly size="mini"></el-input>
                                </el-form-item>
                                <el-form-item label="逻辑分支顺序">
                                    <el-input v-model="staticResultDetailData.calculateBranchNos" placeholder="" readonly size="mini"></el-input>
                                </el-form-item>
                            </div>
                            <div class="display-grid2">
                                <el-form-item label="计算逻辑">
                                    <el-input v-model="staticResultDetailData.calculateLogic" placeholder="" readonly size="mini"></el-input>
                                </el-form-item>
                                <el-form-item label="错误信息">
                                    <el-input v-model="staticResultDetailData.errorMessage" placeholder="" readonly size="mini"></el-input>
                                </el-form-item>
                            </div>
                            <el-form-item label="可投余量">
                                <el-input v-model="computedInvestBalance" placeholder="" readonly size="mini"></el-input>
                                <!-- <el-input v-model="staticResultDetailData.investBalance" placeholder="" readonly size="mini"></el-input> -->
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="dataInfo">
                <vxe-table
                    show-overflow
                    border
                    :expand-config="{ iconOpen: 'el-icon-remove', iconClose: 'el-icon-circle-plus', toggleMethod }"
                    ref="xTable"
                    :auto-resize="true"
                    resizable
                    :data="pageChangeOut1(pageOut1.currentPage, tableDataResultDetail)"
                    @checkbox-all="selectAllValueEvent"
                    @checkbox-change="selectValueChangeEvent"
                    highlight-hover-row
                    :key="renderTable"
                    v-loading="tableLoading"
                    style="width: 100%"
                >
                    <vxe-table-column type="expand" width="50px">
                        <template #content="{ rowIndex }">
                            <div v-if="detailListMsg.returnData.data[rowIndex] && detailListMsg.returnData.data[rowIndex].length > 0">
                                <div class="expand-wrapper">
                                    <vxe-table
                                        :data="showDetailTableData(rowIndex)"
                                        show-header-overflow
                                        :auto-resize="true"
                                        resizable
                                        :filter-config="{ iconNone: 'el-icon-search', iconMatch: 'el-icon-search', remote: true }"
                                        @filter-change="filterHandler($event, rowIndex)"
                                        :sort-config="{ remote: true }"
                                        @sort-change="sortHandler($event, rowIndex)"
                                    >
                                        <!-- :ref="'table' + rowIndex" -->
                                        <!-- :key="tableHandlerInfo[rowIndex].key" -->
                                        <vxe-column
                                            v-for="item in detailListMsg.title[rowIndex]"
                                            :field="item.val"
                                            :title="item.name"
                                            :key="item.val + tableKey"
                                            :min-width="item.minWidth"
                                            :width="item.width"
                                            show-overflow="tooltip"
                                            sortable
                                            :filters="item.filters"
                                        >
                                            <template slot-scope="scope">
                                                <span v-if="item.type === 'func'">
                                                    {{ item.funcBody(scope.row[item.val], scope.row, item.val) }}
                                                </span>
                                                <span v-else>
                                                    {{ handleRowData(scope.row, item.val) }}
                                                </span>
                                            </template>
                                            <template #filter="{ $panel, column }" v-if="item.search">
                                                <div>
                                                    <el-input
                                                        class="my-input"
                                                        type="type"
                                                        v-for="(option, index) in column.filters"
                                                        :key="index"
                                                        v-model="option.data"
                                                        @input="$panel.changeOption($event, !!option.data, option)"
                                                    />
                                                </div>
                                            </template>
                                        </vxe-column>
                                    </vxe-table>
                                </div>
                                <el-pagination
                                    background
                                    layout="total, prev, pager, next"
                                    :total="pageIn1[rowIndex].total"
                                    :page-size="pageIn1[rowIndex].pageSize"
                                    :current-page.sync="pageIn1[rowIndex].currentPage"
                                ></el-pagination>
                            </div>
                            <div v-else class="expand-wrapper"></div>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="resultId" title="序号" min-width="100"></vxe-table-column>
                    <vxe-table-column field="entryCode" title="条目编号"></vxe-table-column>
                    <vxe-table-column field="branchName" title="分支名称"></vxe-table-column>
                    <vxe-table-column field="branchValue" title="分支值" min-width="120">
                        <template #default="{ row }">
                            <span>{{ row.branchValue != undefined ? numberFormatCIB(row.branchValue) : '' }}</span>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="branchNo" title="分支序号"></vxe-table-column>
                    <vxe-table-column field="branchKey" title="静态分支KEY" min-width="120"></vxe-table-column>
                    <vxe-table-column field="entryCalculateFactorCode" title="计算因子" min-width="120">
                        <template slot-scope="scope">
                            {{
                                scope.row.entryCalculateFactorCode +
                                ' ' +
                                (factorPojo[scope.row.entryCalculateFactorCode]
                                    ? factorPojo[scope.row.entryCalculateFactorCode].entryCalculateFactorName
                                    : '')
                            }}
                        </template>
                    </vxe-table-column>
                </vxe-table>
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :total="pageOut1.total"
                    :page-size="pageOut1.pageSize"
                    :current-page.sync="pageOut1.currentPage"
                    v-if="dataOut1.length > pageOut1.pageSize"
                ></el-pagination>
            </div>
        </div>
        <div v-if="promiseListData.length > 0">
            <div v-for="(item, index) in promiseListData" :key="index">
                <div class="header-container-detail">
                    <el-form label-width="100px">
                        <el-collapse>
                            <el-collapse-item>
                                <template slot="title">
                                    <el-row class="backGC">
                                        <el-col :span="24">
                                            <div class="display-grid1">
                                                <el-form-item label="条目编码">
                                                    <el-input v-model="item.staticResult.entryCode" placeholder="" readonly size="mini"></el-input>
                                                </el-form-item>
                                                <el-form-item label="条目名称">
                                                    <el-input v-model="item.staticResult.entryName" placeholder="" readonly size="mini"></el-input>
                                                </el-form-item>
                                                <el-form-item label="估值日期">
                                                    <el-date-picker
                                                        v-model="item.staticResult.tradeDate"
                                                        type="date"
                                                        placeholder="选择日期"
                                                        readonly
                                                        value-format="yyyyMMdd"
                                                        format="yyyy-MM-dd"
                                                        size="mini"
                                                    >
                                                    </el-date-picker>
                                                </el-form-item>
                                                <el-form-item label="触警类型">
                                                    <el-input v-model="item.staticResult.triggerType" readonly size="mini"></el-input>
                                                </el-form-item>
                                            </div>
                                            <div class="display-grid1">
                                                <el-form-item label="计算日期">
                                                    <el-date-picker
                                                        v-model="item.staticResult.calculateDate"
                                                        type="datetime"
                                                        placeholder="选择日期时间"
                                                        readonly
                                                        size="mini"
                                                    >
                                                        <!-- moment(this.state.staticResult.calculateDate + ' ' + this.PrefixInteger(this.state.staticResult.calculateTime, 6), "YYYYMMDD HHmmss").format('YYYY-MM-DD HH:mm:ss')} -->
                                                    </el-date-picker>
                                                </el-form-item>
                                                <el-form-item label="计算结果">
                                                    <el-input v-model="item.staticResult.result" placeholder="" readonly size="mini"></el-input>
                                                </el-form-item>
                                                <el-form-item label="连续违规日期">
                                                    <el-input
                                                        v-model="item.staticResult.prohibitionDate"
                                                        placeholder=""
                                                        readonly
                                                        size="mini"
                                                    ></el-input>
                                                </el-form-item>
                                                <el-form-item label="条目触发值">
                                                    <el-input
                                                        v-model="item.staticResult.thresholdValue"
                                                        placeholder=""
                                                        readonly
                                                        size="mini"
                                                    ></el-input>
                                                </el-form-item>
                                            </div>
                                        </el-col>
                                    </el-row>
                                </template>

                                <el-row style="border-top: 1px solid #ccc">
                                    <el-col :span="24">
                                        <div class="display-grid1">
                                            <el-form-item label="流水号">
                                                <el-input v-model="item.staticResult.resultId" placeholder="" readonly size="mini"></el-input>
                                            </el-form-item>
                                            <el-form-item label="静态条目KEY">
                                                <el-input v-model="item.staticResult.entryKey" placeholder="" readonly size="mini"></el-input>
                                            </el-form-item>
                                            <el-form-item label="条目比较方向">
                                                <el-input v-model="item.staticResult.compareType" readonly size="mini"></el-input>
                                            </el-form-item>
                                            <el-form-item label="逻辑分支顺序">
                                                <el-input
                                                    v-model="item.staticResult.calculateBranchNos"
                                                    placeholder=""
                                                    readonly
                                                    size="mini"
                                                ></el-input>
                                            </el-form-item>
                                        </div>
                                        <div class="display-grid2">
                                            <el-form-item label="计算逻辑">
                                                <el-input v-model="item.staticResult.calculateLogic" placeholder="" readonly size="mini"></el-input>
                                            </el-form-item>
                                            <el-form-item label="错误信息">
                                                <el-input v-model="item.staticResult.errorMessage" placeholder="" readonly size="mini"></el-input>
                                            </el-form-item>
                                        </div>
                                    </el-col>
                                </el-row>
                            </el-collapse-item>
                        </el-collapse>
                    </el-form>
                </div>
                <div class="dataInfo">
                    <vxe-table
                        show-overflow
                        border
                        :expand-config="{ iconOpen: 'el-icon-remove', iconClose: 'el-icon-circle-plus', expandAll: true }"
                        ref="xTable"
                        :auto-resize="true"
                        resizable
                        :data="item.staticBranckResults"
                        @checkbox-all="selectAllValueEvent"
                        @checkbox-change="selectValueChangeEvent"
                        highlight-hover-row
                        :key="renderTable"
                        v-loading="tableLoading"
                    >
                        <vxe-table-column type="expand" width="50px">
                            <template #content="{ rowIndex }">
                                <div v-if="promiseListDetailData[index][rowIndex].length > 0" class="expand-wrapper">
                                    <vxe-table
                                        :data="promiseListDetailData[index][rowIndex]"
                                        :class="'promiseDetail' + rowIndex"
                                        show-header-overflow
                                        resizable
                                        :auto-resize="true"
                                        :filter-config="{ iconNone: 'el-icon-search', iconMatch: 'el-icon-search' }"
                                    >
                                        <vxe-column
                                            v-for="item in promiseDetailListMsg.title[rowIndex]"
                                            :field="item.val"
                                            :title="item.name"
                                            :key="item.val + table2Key"
                                            show-overflow="tooltip"
                                            sortable
                                            :filters="item.filters"
                                            :filter-method="filterHandlerPromise"
                                        >
                                            <template #filter="{ $panel, column }" v-if="item.search">
                                                <div>
                                                    <el-input
                                                        class="my-input"
                                                        type="type"
                                                        v-for="(option, index) in column.filters"
                                                        :key="index"
                                                        v-model="option.data"
                                                        @input="$panel.changeOption($event, !!option.data, option)"
                                                    />
                                                </div>
                                            </template>
                                        </vxe-column>
                                    </vxe-table>
                                </div>
                                <div v-else class="expand-wrapper"></div>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="resultId" title="流水号" min-width="100"></vxe-table-column>
                        <vxe-table-column field="entryCode" title="条目编号"></vxe-table-column>
                        <vxe-table-column field="branchName" title="分支名称"></vxe-table-column>
                        <vxe-table-column field="branchValue" title="分支值" min-width="120">
                            <template #default="{ row }">
                                <span>{{ row.branchValue != undefined ? numberFormatCIB(row.branchValue) : '' }}</span>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="branchNo" title="分支序号"></vxe-table-column>
                        <vxe-table-column field="branchKey" title="静态分支KEY" min-width="120"></vxe-table-column>
                        <vxe-table-column field="entryCalculateFactorCode" title="计算因子" min-width="120">
                            <template slot-scope="scope">
                                {{
                                    scope.row.entryCalculateFactorCode +
                                    ' ' +
                                    (factorPojo[scope.row.entryCalculateFactorCode]
                                        ? factorPojo[scope.row.entryCalculateFactorCode].entryCalculateFactorName
                                        : '')
                                }}
                            </template>
                        </vxe-table-column>
                    </vxe-table>
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts">
import DictionConstUtil from '@/utils/diction-const-util';
import { Component, Vue, Prop } from 'vue-property-decorator';
import RiskTable from '@/common/components/risk-table.vue';
import { lastForOf } from 'xe-utils/methods';
import moment from 'moment';
import {
    getCurrentPageData,
    numberFormat,
    unitShow,
    dateFormat,
    thousandsFormat,
    timeFormat,
    numberFormatXDAY,
    getConfigItem,
    numberFormatCIB,
} from '@/utils/tools';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'StaticResultDetail',
    components: {
        RiskTable,
    },
})
export default class StaticResultDetail extends Vue {
    numberFormat = numberFormat;
    numberFormatXDAY = numberFormatXDAY;
    numberFormatCIB = numberFormatCIB;
    // 详情数据
    @Prop() transToResultDetail;

    // 是否为历史详情
    @Prop() isHistory: boolean;

    WEB_DOCKING = getConfigItem('WEB_DOCKING');

    dateFormat = dateFormat;
    timeFormat = timeFormat;

    private loading: boolean = true; // 是否全部加载

    private tableLoading: boolean = false;

    private isOpen: boolean = false; // 是否展开

    private tableDataResultDetail: any[] = []; // 表格数据

    private renderTable: number = 1; // 表格渲染key

    private compareType: string = ''; // 比较方向

    private triggerType: string = ''; // 触警类型

    private prohibitionDate: string = ''; // 连续违规日期

    private tradeDate: string = ''; // 交易日期

    private factorPojo: any = {}; // 计算因子

    private stockPojo: any = {}; // 证券组

    private fundPojo: any = {}; // 产品组

    private resultInfo: any[] = []; // 单条数据组

    private calculateValue: string = ''; // 计算结果

    private thresholdValue: string = ''; // 触发值

    // 内部分页1
    private pageIn1: any[] = [];

    // 外部分页1
    private pageOut1: pages = {
        pageSize: 100,
        currentPage: 1,
        total: 0,
    };

    // 内部分页2
    private pageIn2: pages = {
        pageSize: 25,
        currentPage: 1,
        total: 0,
    };

    // 外部分页2
    private pageOut2: pages = {
        pageSize: 100,
        currentPage: 1,
        total: 0,
    };

    private staticResultDetailData: any = {
        entryCode: '',
        entryName: '',
        tradeDate: '',
        triggerType: '1',
        calculateDate: '',
        result: '',
        prohibitionDate: 0,
        thresholdValue: '',
        resultId: '',
        entryKey: '',
        compareType: '',
        calculateBranchNos: '',
        calculateLogic: '',
        errorMessage: '',
        investBalance: '',
    };

    private detailListMsg = {
        returnData: { data: [] },
        dataKey: 'data',
        title: [],
    };
    private promiseListData: any[] = [];

    private promiseListDetailData: any[] = [];

    private promiseDetailListMsg = {
        returnData: { data: [] },
        dataKey: 'data',
        title: [],
    };

    // 图标dom
    private iconDom: any = null;
    private table2Key: number = 0;
    private tableKey: number = 0;

    async mounted() {
        // 计算因子
        let factors = (await DictionConstUtil.FNCalculateFactor()) as any;

        for (let value of factors) {
            this.factorPojo[value.entryCalculateFactorCode] = value;
        }

        if (this.transToResultDetail.result != undefined) {
            this.calculateValue =
                numberFormatCIB(this.transToResultDetail.result, this.transToResultDetail.unit) + unitShow(this.transToResultDetail.unit);
        }
        if (this.transToResultDetail.thresholdValue != undefined) {
            this.thresholdValue =
                numberFormatCIB(this.transToResultDetail.thresholdValue, this.transToResultDetail.unit, 'thresholdValue') +
                unitShow(this.transToResultDetail.unit);
        }
        (this.transToResultDetail.dictStockCodes || []).forEach(item => {
            if (item != null) {
                this.stockPojo[item.dictKey] = item.dictKeyName;
            }
        });
        (this.transToResultDetail.dictFundCodes || []).forEach(item => {
            if (item != null) {
                this.fundPojo[item.dictKey] = item.dictKeyName;
            }
        });

        if (
            this.transToResultDetail &&
            this.transToResultDetail.entryCode &&
            this.transToResultDetail.fundCodes &&
            this.transToResultDetail.calculateDate &&
            this.transToResultDetail.calculateTime
        ) {
            let fundCodes = '';
            if (this.transToResultDetail.fundCodes && this.transToResultDetail.fundCodes.length) {
                fundCodes = this.transToResultDetail.fundCodes.join(',');
            }
            const url = this.isHistory ? '/static/history/result/premise/' : '/static/result/premise/';
            this.$axios({
                url:
                    url +
                    this.transToResultDetail.entryCode +
                    '/' +
                    fundCodes +
                    '/' +
                    this.transToResultDetail.calculateDate +
                    '/' +
                    this.transToResultDetail.calculateTime,
                method: 'get',
            }).then((res: any) => {
                if (res && res.length) {
                    res.forEach((item, index) => {
                        if (item.staticResult) {
                            (item.staticResult.dictStockCodes || []).forEach(item => {
                                if (item != null) {
                                    this.stockPojo[item.dictKey] = item.dictKeyName;
                                }
                            });
                            (item.staticResult.dictFundCodes || []).forEach(item => {
                                if (item != null) {
                                    this.fundPojo[item.dictKey] = item.dictKeyName;
                                }
                            });
                        }
                        if (res.staticBranckResults && res.staticBranckResults.length) {
                            res.staticBranckResults.forEach((item, i) => (item.key = item.branchKey + '-' + i));
                            // res.staticBranckResults.sort((a, b) => Number(a.branchNo) - Number(b.branchNo));
                            let calculateBranchNos = this.staticResultDetailData.calculateBranchNos.split(',');
                            let data = calculateBranchNos.map(key => res.staticResultDetailData.find(item => item.branchNo == key));
                            res.staticResultDetailData = data;
                        } else {
                            res.staticBranckResults = [];
                        }
                    });
                    this.promiseListData = res;
                    // 数据显示处理
                    this.promiseListData.forEach((ele, index) => {
                        this.promiseListDetailData[index] = [];
                        ele.staticBranckResults.forEach((ele2, index2) => {
                            this.promiseListDetailData[index][index2] = JSON.parse(ele2.staticDetails || '[]');
                            this.promiseListDetailData[index][index2].length > 0 &&
                                (this.promiseDetailListMsg.title[index2] = this.setTableTitle(ele2));
                            console.log(this.promiseListDetailData, 'this.promiseListDetailData=================');
                        });
                        // 触警类型
                        ele.staticResult.triggerType = DictionConstUtil.ThresholdType[ele.staticResult.triggerType];
                        // 计算日期
                        ele.staticResult.calculateDate = moment(
                            ele.staticResult.calculateDate + ' ' + this.PrefixInteger(ele.staticResult.calculateTime, 6),
                            'YYYYMMDD HHmmss'
                        ).format('YYYY-MM-DD HH:mm:ss');
                        if (ele.staticResult.tradeDate) {
                            ele.staticResult.tradeDate = moment(ele.staticResult.tradeDate, 'YYYYMMDD').format('YYYY-MM-DD');
                        } else {
                            ele.staticResult.tradeDate = '';
                        }
                        // 估值日期
                        ele.staticResult.prohibitionDate = ele.staticResult.prohibitionDate + ' 天';
                        // 条目触发值 计算结果处理
                        if (ele.staticResult.result != '0') {
                            ele.staticResult.result =
                                numberFormat(ele.staticResult.result || '', ele.staticResult.unit) + unitShow(ele.staticResult.unit);
                            ele.staticResult.thresholdValue =
                                numberFormat(ele.staticResult.thresholdValue || '', ele.staticResult.unit) + unitShow(ele.staticResult.unit);
                        } else {
                            ele.staticResult.thresholdValue = ele.staticResult.result;
                        }
                        // 比较方向
                        ele.staticResult.compareType = DictionConstUtil.CompareDirection[ele.staticResult.compareType];
                        // ele.fundNameSt
                    });
                }
            });
        }

        this.staticResultDetailData = JSON.parse(JSON.stringify(this.transToResultDetail));

        this.getBranchByResultId();

        // 比较方向
        this.compareType = DictionConstUtil.CompareDirection[this.staticResultDetailData.compareType];

        // 触警类型
        this.triggerType = DictionConstUtil.ThresholdType[this.staticResultDetailData.triggerType];

        if (this.staticResultDetailData['tradeDate']) {
            this.tradeDate = this.staticResultDetailData['tradeDate'].toString();
        } else {
            this.tradeDate = '';
        }

        this.prohibitionDate = this.staticResultDetailData['prohibitionDate'] + '天';

        this.loading = false;
    }

    get computedInvestBalance() {
        if (this.staticResultDetailData.investBalance && this.getObjectLength(JSON.parse(this.staticResultDetailData.investBalance))) {
            let investBalance = JSON.parse(this.staticResultDetailData.investBalance);
            // let investBalance = { INVESTABLE_BALANCE_1: 47673996.67, INVESTABLE_BALANCE_2: 47673996.67 };
            let investBalanceShow = '';
            let index: number = 0;
            for (const key in investBalance) {
                investBalanceShow += '阀值' + ++index + '可投余量: ' + investBalance['INVESTABLE_BALANCE_' + index] + '，';
            }
            return investBalanceShow.replace(/.$/, '');
        }
        return '';
    }

    // 获取对象长度
    getObjectLength(obj: any) {
        if (obj) {
            return Object.keys(obj).length;
        } else {
            return 0;
        }
    }

    // 点击展开||关闭
    private rotateClick(): void {
        this.isOpen = !this.isOpen;
    }

    // 表格列筛选数据
    filterHandlerPromise({ option, row, column }) {
        const property = column['property'];
        let columnValue: any;
        if (property.indexOf('OBC') != -1) {
            let key1 = property.indexOf('[');
            let key2 = property.indexOf(']');
            let index = property.substring(key1 + 1, key2);
            columnValue = row.OBC[index].columnValue;
        } else {
            columnValue = row[property];
        }
        return columnValue.includes(option.data);
    }

    // expand表格内容
    showDetailTableData(rowIndex) {
        let data = this.detailListMsg.returnData.data[rowIndex];
        let handlerData = data;
        if (this.tableHandlerInfo[rowIndex]) {
            let { property, datas, sortProperty, order } = this.tableHandlerInfo[rowIndex];
            let columnValue: any;
            if (datas.length) {
                handlerData = data.filter(ele => {
                    if (property.indexOf('OBC') != -1) {
                        let key1 = property.indexOf('[');
                        let key2 = property.indexOf(']');
                        let index = property.substring(key1 + 1, key2);
                        columnValue = ele.OBC[index].columnValue;
                    } else {
                        columnValue = ele[property];
                    }
                    return columnValue.includes(datas[0]);
                });
            }
            let type = sortProperty.toString().substr(0, 2);
            if (['N_', 'D_'].includes(type) || sortProperty.indexOf('_TIME') > -1) {
                handlerData = handlerData.slice().sort(this.sortByNum(sortProperty, order));
            } else {
                handlerData = handlerData.slice().sort(this.compareByCh(sortProperty, order));
            }
        }
        // let $ref = this.$refs['table' + rowIndex] as any;
        // console.log($ref, '----');
        // this.$nextTick(()=>{
        //     $ref.updateData()
        // })
        let showData = this.pageChangeIn1(this.pageIn1[rowIndex].currentPage, rowIndex, handlerData);
        return showData;
    }
    tableHandlerInfo = [];
    // 表格列筛选数据
    filterHandler($event, rowIndex) {
        console.log($event, 'option, row, column');

        const { property, datas } = $event;
        // this.tableHandlerInfo[rowIndex] = {
        //     property,
        //     datas,
        //     key: ++this.tableHandlerInfo[rowIndex].key,
        // };
        //  对象引用，为地址赋值.....
        this.tableHandlerInfo[rowIndex].property = property;
        this.tableHandlerInfo[rowIndex].datas = datas;
        // this.tableHandlerInfo[rowIndex].key++;
        this.pageIn1[rowIndex].currentPage = 1;

        console.log(rowIndex, this.tableHandlerInfo[rowIndex].key, this.tableHandlerInfo[rowIndex], 'rowIndex----');

        // return columnValue.includes(option.data);
    }

    sortHandler($event, rowIndex) {
        console.log($event, 'option, row, column');
        const { property, order } = $event;
        this.tableHandlerInfo[rowIndex].sortProperty = property;
        this.tableHandlerInfo[rowIndex].order = order;
    }

    /**
     * 对象数组排序  数字排序
     * @param sortBy 排序字段
     * @param sortType 排序方式
     */
    sortByNum(props, sortType) {
        return function (a, b) {
            // console.log(a[props], b[props], '------');
            let num1 = '';
            let num2 = '';
            if (props.indexOf('OBC') != -1) {
                let key1 = props.indexOf('[');
                let key2 = props.indexOf(']');
                let index = props.substring(key1 + 1, key2);
                num1 = a.OBC[index].columnValue;
                num2 = b.OBC[index].columnValue;
            } else {
                num1 = String(a[props]).replace(/[^\d]/g, '');
                num2 = String(b[props]).replace(/[^\d]/g, '');
            }

            if (sortType?.toUpperCase() == 'DESC') {
                return Number(num2) - Number(num1);
            } else {
                return Number(num1) - Number(num2);
            }
        };
    }

    /**
     * 比较函数 中文排序
     * @param  {string} props 数据里面要排序的key
     * @param  {number} type 1:asc  -1:desc
     * @return {number}
     */
    compareByCh(props, type) {
        type = type?.toUpperCase();
        return function (a, b) {
            let num1 = '';
            let num2 = '';
            if (props.indexOf('OBC') != -1) {
                let key1 = props.indexOf('[');
                let key2 = props.indexOf(']');
                let index = props.substring(key1 + 1, key2);
                num1 = a.OBC[index].columnValue;
                num2 = b.OBC[index].columnValue;
            } else {
                num1 = a[props];
                num2 = b[props];
            }
            if (type == 'ASC') {
                return num1.localeCompare(num2, 'zh-CN', { numeric: true });
            } else if (type == 'DESC') {
                return num2.localeCompare(num1, 'zh-CN', { numeric: true });
            }
        };
    }

    /**
     * 补0方法
     */
    PrefixInteger(num, length) {
        return (Array(length).join('0') + num).slice(-length);
    }

    // 详情
    private getBranchByResultId(): void {
        this.tableLoading = true;
        let history = this.isHistory;
        let url = history ? '/static/history/result/branch/' : '/static/result/branch/';
        this.$axios.get(url + this.transToResultDetail.resultId).then((res: any) => {
            // res = [
            //     {
            //         branchKey: '12:YH1236:5:7:19:0',
            //         branchName: '资产单元净资产',
            //         branchNo: '5',
            //         branchValue: 1000,
            //         entryCalculateFactorCode: 'YH517',
            //         entryCode: 'YH1236',
            //         resultId: 1663461062,
            //         staticDetails: '[{"N_NET_ASSET":1000,"C_FUND_CODE":"2001","C_ASSET_CODE":"19"}]',
            //     },
            //     {
            //         branchKey: '12:YH1236:3:7:19:0',
            //         branchName: '证券持仓市值',
            //         branchNo: '3',
            //         branchValue: 300,
            //         entryCalculateFactorCode: 'YH801',
            //         entryCode: 'YH1236',
            //         resultId: 1663461062,
            //         staticDetails:
            //             '[{"C_FUND_CODE":"2001","D_POSITION_DATE":20210129,"N_MARKET_VALUE":100,"C_STOCK_CODE":"600019 SS","C_ISSUE_CODE":"1046","N_POSITION_ID":117838300,"C_ASSET_CODE":"19","C_ORIGINAL_HOLDER":"1046"},{"C_FUND_CODE":"2001","D_POSITION_DATE":20210129,"N_MARKET_VALUE":100,"C_STOCK_CODE":"163847 SS","C_ISSUE_CODE":"41126","N_POSITION_ID":121,"C_ASSET_CODE":"19"},{"C_FUND_CODE":"2001","D_POSITION_DATE":20210129,"N_MARKET_VALUE":100,"C_STOCK_CODE":"164847 SS","N_POSITION_ID":45,"C_ASSET_CODE":"19"}]',
            //     },
            // ];
            if (res && res.length > 0) {
                res.forEach((item, i) => (item.key = item.branchKey + '-' + i));
                // res.sort((a, b) => Number(a.branchNo) - Number(b.branchNo));

                let calculateBranchNos = this.staticResultDetailData.calculateBranchNos.split(',');
                let data = calculateBranchNos.map(key => res.find(item => item.branchNo == key));
                res = data;

                this.tableDataResultDetail = res;

                this.renderTable++;

                for (let i = 0; i < res.length; i++) {
                    this.detailListMsg.returnData.data[i] = JSON.parse(res[i].staticDetails);

                    if (this.detailListMsg.returnData.data[i].length) {
                        this.detailListMsg.title[i] = this.setTableTitle(this.tableDataResultDetail[i]);
                        this.detailListMsg.returnData.data[i].forEach(item => {
                            item.C_STOCK_CODE = item.C_STOCK_CODE + '(' + this.stockPojo[item.C_STOCK_CODE] + ')';
                            const fundName = this.fundPojo[item.C_FUND_CODE];
                            item.C_FUND_CODE = item.C_FUND_CODE + (fundName ? '(' + fundName + ')' : '');
                        });
                    }

                    this.pageIn1.push({
                        currentPage: 1,
                        pageSize: 25,
                        total: 0,
                    });
                    this.tableHandlerInfo.push({ property: '', datas: [], key: 0, sortProperty: '', order: '' });
                }
            }
            this.tableLoading = false;
        });
    }

    // 转字符串
    private getDetailListMsgStr(valueObj: any, keys: any): void {
        for (let item of keys) {
            if (item.val === 'C_FUND_CODE') {
                this.resultInfo.push({
                    dictKey: item.val,
                    dictKeyName: item.name,
                    dictValue: valueObj[item.val] + (this.fundPojo[valueObj[item.val]] ? '(' + this.fundPojo[valueObj[item.val]] + ')' : ''),
                });
            } else if (item.val === 'C_STOCK_CODE') {
                this.resultInfo.push({
                    dictKey: item.val,
                    dictKeyName: item.name,
                    dictValue: valueObj[item.val] + (this.stockPojo[valueObj[item.val]] ? '(' + this.stockPojo[valueObj[item.val]] + ')' : ''),
                });
            } else {
                this.resultInfo.push({
                    dictKey: item.val,
                    dictKeyName: item.name,
                    dictValue: valueObj[item.val],
                });
            }
        }
    }

    // 设置表头属性
    private setTableTitle(staticBranch: any) {
        // 优先展示字段，使用正则替换排序，不支持小数
        let fieldSort = ['C_FD_PRODUCT_CODE', 'C_FUND_CODE', 'C_STOCK_CODE'];
        // 除去优先展示的字段 其余字段使用正则排序的字段排序字段 不支持小数
        let fieldNoSort = ['C_PRODUCT_CODE'];

        let factor = this.factorPojo[staticBranch.entryCalculateFactorCode];
        if (!factor) {
            this.yh_message_error('未找到相关计算因子,分支明细解析失败！');
            return [];
        }
        try {
            // 静态字段
            let staticCalConfig = factor.staticCalConfig.split(';');
            // 字段对应名称
            let columnsNames = factor.columnsNames.split(';');

            let descript = {};
            console.log(columnsNames, 'columnsNames');

            for (let i = 0; i < columnsNames.length; i++) {
                let tablename = columnsNames[i]
                    .substr(0, columnsNames[i].indexOf(':'))
                    .replace(/\\r\\n/g, '')
                    .trim();
                let fields = columnsNames[i].substr(columnsNames[i].indexOf(':') + 1).split(',');
                this.$set(descript, tablename, {});
                for (let j = 0; j < fields.length; j++) {
                    descript[tablename][fields[j].substr(0, fields[j].indexOf('\\'))] = fields[j].substr(fields[j].indexOf('\\') + 1);
                }
            }
            let columnfield = descript[staticCalConfig[0]];
            let columns = [];
            for (let key in columnfield) {
                if (fieldSort.includes(key)) {
                    continue;
                }
                if (fieldNoSort.includes(key)) {
                    columns.push({
                        name: columnfield[key],
                        val: key,
                        minWidth: 150,
                    });
                } else {
                    columns.push({
                        name: columnfield[key],
                        val: key,
                        minWidth: 150,
                        type: 'func',
                        funcBody: (value, row, val) =>
                            value != undefined && val.toString().substr(0, 2) == 'N_'
                                ? numberFormat(value)
                                : val.indexOf('_TIME') > -1
                                ? timeFormat(value)
                                : val.toString().substr(0, 2) == 'D_'
                                ? dateFormat(value)
                                : value || '--',
                    });
                }
            }

            // 优先展示字段
            for (let i = fieldSort.length - 1; i > -1; i--) {
                if (columnfield[fieldSort[i]]) {
                    columns.unshift({
                        name: columnfield[fieldSort[i]],
                        val: fieldSort[i],
                        width: 150,
                        search: true,
                        filters: [{ data: '' }],
                    });
                }
            }

            // obc字段
            if (staticBranch && staticBranch.staticDetails && staticBranch.staticDetails !== '[]') {
                let staticDetails = JSON.parse(staticBranch.staticDetails);
                if (staticDetails && staticDetails.length > 0 && staticDetails[0].OBC) {
                    for (let i = 0; i < staticDetails[0].OBC.length; i++) {
                        let extraFieldData = staticDetails[0].OBC[i];
                        columns.push({
                            name: extraFieldData.columnDesc ? extraFieldData.columnDesc : '未知',
                            val: 'OBC[' + i + '].columnValue',
                            width: 200,
                            search: true,
                            filters: [{ data: '' }],
                        });
                    }
                }
            }
            columns = columns.filter(ele => !['持仓编号', '持仓序号'].includes(ele.name));
            return columns;
        } catch (e) {
            // this.yh_message_error('分支明细解析失败！');
            console.log(e);
            return [];
        }
    }

    private dataIn1: any = {}; // 内部分页1
    private dataOut1: any[] = []; // 外部分页1

    // 内部分页1
    private pageChangeIn1(currentPage: number, index: number, data: any): any {
        console.log(currentPage, 'currentPage');
        this.pageIn1[index].total = data.length;
        this.$set(this.dataIn1, index, data);
        let retValue = getCurrentPageData(data, currentPage, this.pageIn1[index].pageSize);
        return retValue;
    }

    // 外部分页1
    private pageChangeOut1(currentPage: number, data: any): any {
        this.pageOut1.total = data.length;
        this.dataOut1 = data;
        let retValue = getCurrentPageData(data, currentPage, this.pageOut1.pageSize);
        return retValue;
    }
    // 内部分页2

    // 外部分页2

    private selectAllValueEvent(): void {}

    private selectValueChangeEvent(): void {}

    // 处理显示字段内容
    private handleRowData(row: any, val: string) {
        if (val.indexOf('OBC') != -1) {
            let key1 = val.indexOf('[');
            let key2 = val.indexOf(']');
            let index = val.substring(key1 + 1, key2);
            return parseFloat(row.OBC[index].columnValue) > 0 ? parseFloat(row.OBC[index].columnValue) : row.OBC[index].columnValue;
        } else {
            return row[val];
        }
    }

    getCalcDateTime(staticResultDetailData) {
        let value = dateFormat(staticResultDetailData['calculateDate']) + ' ' + timeFormat(staticResultDetailData['calculateTime']);
        return dateFormat(staticResultDetailData['calculateDate']) + ' ' + timeFormat(staticResultDetailData['calculateTime']);
    }
}
</script>
<style lang="scss" scoped>
.container {
    padding: 0 20px 20px 20px;
    .header-container-detail {
        border: 1px solid #ccc;
    }
    .dataInfo {
        margin-top: 10px;
    }
    .display-grid1 {
        display: grid;
        grid-template-columns: 25% 25% 25% 25%;
        height: 40px;
    }
    .display-grid2 {
        display: grid;
        grid-template-columns: 50% 50%;
        height: 40px;
    }
    .backGC {
        background-color: #f7f7f7;
        width: 100%;
    }
    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
        width: 100% !important;
    }
    .boxStyle {
        margin: 40px 0 0 10px;
        width: 40px;
        height: 40px;
    }
    .iconStyle {
        color: #939398;
        font-size: 22px;
    }
}

/deep/ .vxe-table--render-default .vxe-table--expanded .vxe-table--expand-btn {
    font-size: 20px;
}

/deep/ .vxe-table--render-default .vxe-body--expanded-cell {
    margin-left: 49px;
    padding: 0;
}

/deep/ .vxe-table .vxe-table--body-wrapper.body--wrapper {
    height: calc(100vh - 210px);
    min-height: 0;
    overflow-x: hidden; //
}

.expand-wrapper {
    padding-bottom: 6px;

    /deep/ .vxe-table .vxe-table--body-wrapper.body--wrapper {
        overflow: auto;
        max-height: calc(100vh - 315px);
        height: fit-content;
        min-height: 70px;
    }
}

/deep/.el-collapse-item__header {
    height: fit-content !important;
}

/deep/ .el-pagination {
    padding: 8px 8px 8px 0px !important;
}
</style>
